/**
 * 提供角色管理的增删改查接口，并自定了异常回调函数
 *     create(role: any): Promise<any> {...}增
 *     delete(id: number): Promise<any> {...}删
 *     update(role: any): Promise<any> {...}改
 *     getRoles(type, pn, ps): Promise<any> {...}查
 *     save(role: any): Promise<any> {...}封装增，改接口，当增加或者修改时，调用此方法
 */
import {Injectable} from '@angular/core';
import {Headers, Http, RequestOptions, URLSearchParams} from "@angular/http";
import './../../../../../rxjs-operators'; // Operators
@Injectable()
export class RoleService {
  private headers = new Headers({'Content-Type': 'application/json'}); // set body as json
  private url = '/api/role';

  constructor(private http: Http) {
  }

  create(role: any): Promise<any> {
    let options = new RequestOptions({headers: this.headers});
    const url = `${this.url}`;
    return this.http
      .put(this.url, JSON.stringify(role), options)
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }

  delete(id: number): Promise<any> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url, {headers: this.headers})
      .toPromise()
      .then((res) => res.json())
      .catch(this.handleError);
  }

  update(role: any): Promise<any> {
    let options = new RequestOptions({headers: this.headers});
    const url = `${this.url}`;
    return this.http
      .post(this.url, JSON.stringify(role), options)
      .toPromise()
      .then(res => res.json())
      .catch(this.handleError);
  }

  getRoles(type, pn, ps): Promise<any> {
    let params = new URLSearchParams();
    params.set('pn', pn);
    params.set('ps', ps);
    params.set('type', type);
    return this.http.get(this.url, {search: params}).toPromise().then(response => {
      return response.json()
    });
  }

  save(role: any): Promise<any> {
    if (role.id) {
      return this.update(role);
    } else {
      return this.create(role);
    }
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}
